package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class FriendApiImpl implements FriendApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /*双向添加好友关系*/
    @Override
    public void addContacts(Long userId, Long friendId) {
        //添加当前用户的好友信息
        //判断好友关系是否存在
        Query query1 = Query.query(Criteria.where("userId")
                .is(userId).and("friendId").is(friendId));
        boolean result1 = mongoTemplate.exists(query1, Friend.class);
        //不存在则保存
        if(!result1){
            Friend friend1 = new Friend();
            friend1.setUserId(userId);
            friend1.setFriendId(friendId);
            friend1.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend1);
        }


        //添加好友的好友信息
        //判断好友关系是否存在
        Query query2 = Query.query(Criteria.where("userId")
                .is(friendId).and("friendId").is(userId));
        boolean result2 = mongoTemplate.exists(query2, Friend.class);
        //不存在则保存
        if(!result2){
            Friend friend2 = new Friend();
            friend2.setUserId(friendId);
            friend2.setFriendId(userId);
            friend2.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend2);
        }
    }

    /*获得用户好友信息分页列表*/
    @Override
    public List<Friend> findByUserId(Long userId, Integer page, Integer pagesize) {
        //构造查询条件
        Criteria criteria = Criteria.where("userId").is(userId);
        //构造分页和排序条件
        Query query = Query.query(criteria).skip((page - 1) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        //调用mongoTemplate进行查询
        List<Friend> list = mongoTemplate.find(query, Friend.class);
        //返回结果
        return list;
    }
}
